package com.aos.iot.protocol.hll.parser.data;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.aos.iot.protocol.hll.constant.HllCmd;
import com.aos.iot.protocol.hll.constant.HllProp;
import com.aos.iot.protocol.hll.util.CodeUtil;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("ConfirmUpgradeDataParser")
public class ConfirmUpgradeDataParser extends HllDataParser {

    private final List<String> encodeItems = CollUtil.newArrayList(
        HllProp.PILE_NO.getValue(),
        HllProp.SYSTEM_UPGRADE_TYPE.getValue(),
        HllProp.PIPE_SOFT_VERSION.getValue(),
        HllProp.PILE_SOFT_VERSION.getValue(),
        HllProp.SYSTEM_RETURN_STATUS.getValue()
    );

    private final List<String> decodeItems = CollUtil.newArrayList(
        HllProp.PILE_NO.getValue(),
        HllProp.SYSTEM_UPGRADE_TYPE.getValue(),
        HllProp.PIPE_SOFT_VERSION.getValue(),
        HllProp.PILE_SOFT_VERSION.getValue(),
        HllProp.SYSTEM_UPGRADE_WAY.getValue(),
        HllProp.SYSTEM_UPGRADE_FILE_SIZE.getValue()
    );

    @Override
    public Dict encode(String payload) {
        String upgradeType = sub(payload, 10, 12, false, "00");
        String softVersion = StrUtil.equalsIgnoreCase("02", upgradeType) ?
                HllProp.PIPE_SOFT_VERSION.getValue() : HllProp.PILE_SOFT_VERSION.getValue();
        return Dict.create()
                .set(HllProp.PILE_NO.getValue(), sub(payload, 0, 10, true, "0000000000"))
                .set(HllProp.SYSTEM_UPGRADE_TYPE.getValue(), upgradeType)
                .set(softVersion, sub(payload, 12, 14, false, "00"))
                .set(HllProp.SYSTEM_RETURN_STATUS.getValue(), sub(payload, 14, 16, false, "01"))
                .set(HllProp.SYSTEM_UPGRADE_WAY.getValue(), sub(payload, 16, 18, false, "99"))
                ;
    }

    @Override
    public List<String> encodeItems() {
        return encodeItems;
    }

    @Override
    public String decode(Dict data) {
        String upgradeType = data.getStr(HllProp.SYSTEM_UPGRADE_TYPE.getValue());
        String softVersion = StrUtil.equalsIgnoreCase("02", upgradeType) ?
                HllProp.PIPE_SOFT_VERSION.getValue() : HllProp.PILE_SOFT_VERSION.getValue();
        return StrUtil.join("",
                data.getStr(HllProp.PILE_NO.getValue()),
                upgradeType,
                data.get(softVersion, "00"),
                data.getStr(HllProp.SYSTEM_UPGRADE_WAY.getValue()),
                CodeUtil.highRotation(data.getStr(HllProp.SYSTEM_UPGRADE_FILE_SIZE.getValue()))
        );
    }

    @Override
    public List<String> decodeItems() {
        return decodeItems;
    }

    @Override
    public String cmd() {
        return HllCmd.OTA_VERSION_UPDATE;
    }
}
